<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import {
  noticePageList,
  addNotice,
  noticeInfo,
  noticeDel,
  editNotice
} from "@/api/content";
import { noticeQuery, noticeList, noticeForm } from "@/api/content/types";
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatTimestamp } from '@/utils/index'
// 富文本
import Editor from "@/components/WangEditor/index.vue";


const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<noticeQuery>({
  page: 1,
  ps: 10,
});

const dataList = ref<noticeList[]>();

// 获取表单
const menuFormRef = ref(ElForm);

// 表单提交数据
const formData = reactive<noticeForm>({
  title: '',
  show_status: 1,
  sort: 0,
  content: ''
});

// 表单验证
const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  show_status: [{ required: true, message: "选择状态", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  noticePageList(queryParams)
    .then(({ data }) => {
      dataList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

let typeDialog = ref<any>('');
// 打开弹窗
const openDialog = (postId?: number | string, type?: string) => {
  dialog.visible = true;
  typeDialog.value = type;

  if (postId) {
    dialog.title = "修改公告";
    noticeInfo({ id: postId }).then(res => {
      Object.assign(formData, res.data.info);
    })
  } else {
    dialog.title = "新增公告";
  }
}

// 确认提交
const submitForm = () => {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (formData.id) {
        editNotice(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })

      } else {
        addNotice(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      }
    }
  })
}

/** 删除菜单 */
function handleDelete(menuId: number) {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    noticeDel({ ids: [menuId] }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.id = undefined;
  formData.title = '';
  formData.sort = 0;
  formData.show_status = 1;
  formData.content = '';
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="标题" prop="s_title">
              <el-input v-model="queryParams.s_title" placeholder="标题关键字查询" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="账户状态" prop="show_status">
              <el-select v-model="queryParams.show_status" placeholder="选择是否显示" clearable style="width: 200px"
                @change="handleQuery">
                <el-option label="显示" value="1" />
                <el-option label="不显示" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button v-hasPerm="['notice:add']" @click="openDialog()" type="primary"><i-ep-plus />新增公告</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" :data="dataList" v-hasPerm="['notice:pageList']">
            <el-table-column label="id" align="center" prop="id" width="100" />
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column label="标题" align="center" prop="title" />
            <el-table-column label="标题" align="center">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.show_status == 1">显示</el-tag>
                <el-tag type="danger" v-else-if="scope.row.show_status == 2">隐藏</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="created_at">
              <template #default="scope">
                <template v-if="scope.row.created_at > 0">
                  {{ formatTimestamp(scope.row.created_at * 1000) }}
                </template>
              </template>
            </el-table-column>

            <el-table-column fixed="right" align="center" label="操作" width="220">
              <template #default="scope">
                <el-button v-hasPerm="['notice:detail']" type="primary" link size="small"
                  @click.stop="openDialog(scope.row.id, 'info')">详情</el-button>
                <el-button v-hasPerm="['notice:update']" type="primary" link size="small"
                  @click.stop="openDialog(scope.row.id, 'edit')">修改</el-button>
                <el-button v-hasPerm="['notice:del']" type="primary" link size="small"
                  @click.stop="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="60%"
      @close="closeDialog">
      <el-form ref="menuFormRef" :disabled="typeDialog == 'info' ? true : false" :model="formData" :rules="rules"
        label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="show_status">
          <el-radio-group v-model="formData.show_status">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="2">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="formData.content" class="border" style="height:500px;" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer" v-if="typeDialog != 'info'">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.border {
  border: 1px solid #dcdfe6;
  border-radius: 10rpx;
  overflow: hidden;
}

:deep() {
  .w-e-text-container {
    height: 410px !important;
  }
}
</style>